package com.ky.manage.activity.indoor;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ky.manage.R;
import com.ky.manage.activityLifecycle.ActivityManagerUtil;
import com.ky.manage.adapter.PicAddAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.DocInfo;
import com.ky.manage.model.response.CommonResp;
import com.ky.manage.model.response.IndoorCheckItemListResp;
import com.ky.manage.model.response.UploadFileInfoResp;
import com.ky.manage.permission.AndPermissionUtils;
import com.ky.manage.ui.CheckItemView;
import com.ky.manage.ui.dialog.CommonDialog;
import com.ky.manage.utils.ImageLoader.GlideEngine;
import com.ky.manage.utils.ReClickHelper;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.ky.manage.utils.log.ObjectUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cz.msebera.android.httpclient.Header;

import static com.ky.manage.activity.indoor.ClientSignActivity.SIGN_INDOOR_SECURITY_CHECK;

/**
 * 新增安检记录
 * 户内安检详情页
 */
public class IndoorSecurityCheckAddDetailActivity extends BaseActivity {
    private LinearLayout checkListViewGroup;
    private RecyclerView mPicRecyclerView;
    private List<LocalMedia> mPicSelectMediaList = new ArrayList<>();
    private PicAddAdapter mPicAddAdapter;
    private String mIndoorId = "";
    private List<DocInfo> mUploadedDocInfoList = new ArrayList<>();

    public static void toSecurityCheckAddDetailActivity(BaseActivity activity, String id) {
        Intent intent = new Intent(activity, IndoorSecurityCheckAddDetailActivity.class);
        intent.putExtra("id", id);
        activity.toActivity(intent);
        activity.finish();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_indoor_security_check_add_detail;
    }

    @Override
    protected void initView() {
        findTextView(R.id.page_title_tv, "户内安检-安检信息");
        findView(R.id.back_iv, v -> {
            finish();
        });
        findView(R.id.next_sign_tv, v -> {
            //下一步，客户签字
            if (mPicSelectMediaList.size() <= 1) {
                ToastUtils.showRoundRectToast("请添加现场图片");
                return;
            }
            if (ZyUtils.getInstance().isNetConnected()) {
                ZyUtils.getInstance().showLoadingDialog(this, "");
                mNeedUploadImgList.clear();
                mNeedUploadImgList.addAll(mPicSelectMediaList);
                Log.d("lhm", "mPicSelectMediaList size = " + mPicSelectMediaList.size());
                mNeedUploadImgList.remove(0);
                Log.d("lhm", "mNeedUploadImgList size = " + mNeedUploadImgList.size());
                uploadLoadImg(()->{
                    updateIndoorInfo();
                });
            }
        });

        checkListViewGroup = findView(R.id.check_list_ll);
        initPicListView();
    }

    private void initPicListView() {
        mPicSelectMediaList.add(new LocalMedia());
        mPicRecyclerView = findView(R.id.pic_list_view);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mPicRecyclerView.setLayoutManager(manager);
        mPicAddAdapter = new PicAddAdapter(R.layout.layout_pic_item_filter, mPicSelectMediaList);
        mPicRecyclerView.setAdapter(mPicAddAdapter);
        mPicAddAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mPicSelectMediaList.size() > 0) {
                LocalMedia media = mPicSelectMediaList.get(position);
                if (null == media.getPath()) {
                    //添加图片
                    selectPic();
                    return;
                }
                //"image/jpeg"
                String mimeType = media.getMimeType();
                PictureSelector.create(IndoorSecurityCheckAddDetailActivity.this)
                        .externalPicturePreview(position -1, getPreviewMediaList(mPicSelectMediaList), 0);
            }
        });
    }

    private void updateIndoorInfo() {
        RequestParams requestParams = new RequestParams();
        try {
            File[] files = new File[mNeedUploadImgList.size()];
            for (int i = 0; i< mNeedUploadImgList.size(); i++) {
                LocalMedia localMedia = mNeedUploadImgList.get(i);
                files[i] = new File(localMedia.getPath()); //getRealPathFromUri(this, Uri.parse(localMedia.getPath()))
            }
            requestParams.put("docList", new Gson().toJson(mUploadedDocInfoList));
            requestParams.put("indoorId", Integer.parseInt(mIndoorId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        ZyUtils.getInstance().insertLog("updateIndoorInfo", "appApi/indoorUpdate req = "
                + requestParams.toString());
        Log.d("lhm", "updateIndoorInfo req param = " + requestParams.toString());
        AsyncHttpUtils.getInstance().put(this, BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/indoorUpdate", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("updateIndoorInfo", "onFailure statusCode = "
                        + statusCode + ", responseString = " + responseString);
                ToastUtils.showRoundRectToast("服务器异常，请稍候重试");
                Log.d("lhm", "indoorUpdate responseString = " + responseString);
                ZyUtils.getInstance().hideLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("updateIndoorInfo", "onSuccess statusCode = "
                        + statusCode + ", responseString = " + responseString);
                ZyUtils.getInstance().hideLoadingDialog();
                CommonResp resp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, CommonResp.class);
                if (statusCode == 200 && null != resp && resp.code == 200) {
                    finish();
                    ClientSignActivity.toClientSignActivity(mCurActivity, mIndoorId, SIGN_INDOOR_SECURITY_CHECK);
                } else {
                    ToastUtils.showRoundRectToast("服务器异常，请稍候重试");
                }
            }
        });
    }

    private List<LocalMedia> mNeedUploadImgList = new ArrayList<>();
    private int mCurUploadImgIndex = 0;

    public interface UploadAllImgCallback {
        void onUploadSuccess();
    }

    /**
     * 图片上传
     * @param uploadAllImgCallback
     */
    private void uploadLoadImg(UploadAllImgCallback uploadAllImgCallback) {
        ZyUtils.getInstance().insertLog("uploadLoadImg", "mCurUploadImgIndex = " + mCurUploadImgIndex
                + ", mNeedUploadImgList size = " + mNeedUploadImgList.size());
        if (mCurUploadImgIndex >= mNeedUploadImgList.size()) {
            //图片上传完成，最终接口上传合并
            if (null != uploadAllImgCallback) {
                uploadAllImgCallback.onUploadSuccess();
            }
            return;
        }
        LocalMedia localMedia = mNeedUploadImgList.get(mCurUploadImgIndex);
        Log.d("lhm", "uploadLoadImg path = " + localMedia.getPath());
        String localMediaPath = localMedia.getPath();//getRealPathFromUri(this, Uri.parse(localMedia.getPath()));
        ZyUtils.getInstance().insertLog("uploadLoadImg", "localMediaPath = " + localMediaPath);
        BusinessHttpReqUtils.getInstance().uploadFile(new File(localMediaPath), new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("uploadLoadImg", "onFailure statusCode = " + statusCode
                        + ", responseString = " + responseString);
                ToastUtils.showRoundRectToast("上传文件失败：" + responseString);
                ZyUtils.getInstance().hideLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("uploadLoadImg", "onSuccess statusCode = " + statusCode
                        + ", response = " + responseString);
                UploadFileInfoResp fileInfoResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, UploadFileInfoResp.class);
                if (null != fileInfoResp && fileInfoResp.code == 200) {
                    //上传成功
                    String url = fileInfoResp.url.replace("\\", "");
                    DocInfo docInfo = new DocInfo();
                    docInfo.docUrl = url;
                    docInfo.docName = fileInfoResp.fileName;
                    mUploadedDocInfoList.add(docInfo);
                    ++mCurUploadImgIndex;
                    uploadLoadImg(uploadAllImgCallback);
                } else {
                    ToastUtils.showRoundRectToast("上传文件失败");
                    ZyUtils.getInstance().hideLoadingDialog();
                }
            }
        });
    }

    /**
     * 获取图片路径
     * @param media
     * @return
     */
    public String getPathFromLocalMedia(LocalMedia media) {
        if (media == null || TextUtils.isEmpty(media.getPath())) {
            return null;
        }
        String path;
        if (media.isCut() && !media.isCompressed()) {
            // 裁剪过
            path = media.getCutPath();
        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = media.getCompressPath();
        } else {
            // 原图地址
            path = media.getPath();
        }
        return path;
    }

    public String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private List<LocalMedia> getPreviewMediaList(List<LocalMedia> mediaList) {
        List<LocalMedia> previewMediaList = new ArrayList<>();
        for (int i = 1; i < mediaList.size(); i++) {
            previewMediaList.add(mediaList.get(i));
        }
        return previewMediaList;
    }

    private void selectPic() {
        if (ReClickHelper.clickEnable()) {
            AndPermissionUtils.getInstance().requestCameraPermission(this, () -> {
                showAddPicDialog();
            });
        }
    }

    private CommonDialog mAddPicDialog;

    /**
     * 添加图片选择框
     */
    private void showAddPicDialog() {
        if (ActivityManagerUtil.getInstance().isActivityDestroy(this)) {
            return;
        }
        if (null == mAddPicDialog) {
            WeakReference<FragmentActivity> activityWeakReference = new WeakReference<>(this);
            mAddPicDialog = CommonDialog.create(activityWeakReference.get().getSupportFragmentManager())
                    .setLayoutRes(R.layout.dialog_add_pic)
                    .setViewListener(((v, baseDialog) -> {
                        if (null == activityWeakReference || null == activityWeakReference.get()
                                || activityWeakReference.get().isFinishing()) {
                            return;
                        }
                        TextView addPicFromCamera = v.findViewById(R.id.add_pic_camera);
                        TextView addPicFromAlbum = v.findViewById(R.id.add_pic_album);
                        TextView cancelTv = v.findViewById(R.id.cancel_tv);
                        addPicFromCamera.setOnClickListener(v1 -> {
                            //拍照获取图片
                            if (ReClickHelper.clickEnable()) {
                                //拍照
                                PictureSelector.create(IndoorSecurityCheckAddDetailActivity.this)
                                        .openCamera(PictureMimeType.ofImage())
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                hideAddPicDialog();
                            }
                        });
                        addPicFromAlbum.setOnClickListener(v1 -> {
                            //从相册获取图片
                            if (ReClickHelper.clickEnable()) {
                                PictureSelector.create(IndoorSecurityCheckAddDetailActivity.this)
                                        .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                        .maxSelectNum(Integer.MAX_VALUE)// 最大图片选择数量
                                        .minSelectNum(1)// 最小选择数量
                                        .imageSpanCount(4)// 每行显示个数
                                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
                                        .imageEngine(GlideEngine.createGlideEngine())
                                        .isPreviewImage(true)// 是否可预览图片
                                        .isCamera(true)// 是否显示拍照按钮
                                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
//                                        .setOutputCameraPath(Environment.getExternalStorageDirectory().getPath()
//                                                + "/ky/tmpPath/")// 自定义拍照保存路径
                                        .isEnableCrop(false)// 是否裁剪
                                        .isCompress(false)// 是否压缩
                                        //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                        .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                                        .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                                        //.selectionMedia(selectList)// 是否传入已选图片
                                        //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                        //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                                        //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                                        //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                                        //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                                        .rotateEnabled(false) // 裁剪是否可旋转图片
                                        //.scaleEnabled()// 裁剪是否可放大缩小图片
                                        //.recordVideoSecond()//录制视频秒数 默认60s
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                hideAddPicDialog();
                            }
                        });
                        cancelTv.setOnClickListener(v1 -> {
                            //关闭弹框
                            hideAddPicDialog();
                        });
                    }))
                    .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
                    .setGravity(Gravity.CENTER)
                    .setOnDismissListener(dialog -> {
                        //对话框关闭
                        hideAddPicDialog();
                    })
                    .setDialogWidth(ScreenUtils.dp2px(300))
                    .setDimAmount(0.2f)
                    .setCancelOutside(false)
                    .setKeyBackDismiss(false)
                    .setTag("AddPicDialog");
        }

        if (mAddPicDialog.isShowing()) {
            return;
        }
        mAddPicDialog.show();
    }

    private void hideAddPicDialog() {
        if (null != mAddPicDialog) {
            mAddPicDialog.dismissAllowingStateLoss();
            mAddPicDialog = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (requestCode == PictureConfig.CHOOSE_REQUEST){
            List<LocalMedia> images;
            if (resultCode == RESULT_OK) {
                if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    Log.d("lhm", "images size = " + images.size());
                    if (null == images || images.size() == 0) {
                        return;
                    }
                    mPicSelectMediaList.addAll(images);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    mPicAddAdapter.setList(mPicSelectMediaList);
                    mPicAddAdapter.notifyDataSetChanged();
                }
            }
        } else {
            if (resultCode == RESULT_OK) {
                //更新数据
                ZyUtils.getInstance().insertLog("onActivityResult", "sCurModifyCheckItem = "
                        + ObjectUtil.objectToString(OverallData.sCurModifyCheckItem));
                if (null != mCurModifyCheckItemView) {
                    mCurModifyCheckItemView.setStateTxt("0".equals(OverallData.sCurModifyCheckItem.isQuestion) ? "是" : "否");
                }
            }
        }
    }

    @Override
    protected void initData() {
        mIndoorId = getIntent().getStringExtra("id");
        Log.d("zhaoyan", "mIndoorId = " + mIndoorId);

        //获取检测项
        BusinessHttpReqUtils.getInstance().requestIndoorCheckItemListInfo(mIndoorId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("getProjectList", "onFailure statusCode = "
                        + statusCode + ", responseString = " + responseString);
                ToastUtils.showRoundRectToast("服务器异常，获取检测项目失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("getProjectList", "onSuccess statusCode = "
                        + statusCode + ", responseString = " + responseString);
                if (statusCode == 200) {
                    IndoorCheckItemListResp itemListResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, IndoorCheckItemListResp.class);
                    if (null != itemListResp && itemListResp.code == 200) {
                        initCheckListResult(itemListResp.rows);
                    } else {
                        ToastUtils.showRoundRectToast("服务器异常，获取检测项目失败");
                    }
                } else {
                    ToastUtils.showRoundRectToast("服务器异常，获取检测项目失败");
                }
            }
        });
    }

    /**
     * 检测条目列表
     * @param rows
     */
    private void initCheckListResult(List<IndoorCheckItemListResp.CheckItemInfo> rows) {
        checkListViewGroup.removeAllViews();
        if (null != rows && !rows.isEmpty()) {
            for (int i = 0; i < rows.size(); i++) {
                IndoorCheckItemListResp.CheckItemInfo checkItemInfo = rows.get(i);
                CheckItemView checkItemView = new CheckItemView(this);
                checkItemView.setLabelTxt(checkItemInfo.projectName);
                //是否有问题（0是， 1否）
                checkItemView.setStateTxt("0".equals(checkItemInfo.isQuestion) ? "是" : "否");
                checkItemView.setOnClickListener(v -> {
                    checkItemInfo.indoorId = mIndoorId;
                    mCurModifyCheckItemView = checkItemView;
                    IndoorProjectItemEditActivity.toIndoorProjectItemEditPage(this, checkItemInfo);
                });
                checkListViewGroup.addView(checkItemView);
            }
        }
    }

    private CheckItemView mCurModifyCheckItemView = null;
}